/**
 * Created by wndwl on 2016/11/10.
 */
(function($){
    $.fn.waterFall=function(options){
        var defaults={
            boxWidth : "95%",
            columnWidth : "25%",
            spacing : "5px",
            random : false,
            imgUrlPrefix : ""
        };
        var opts = $.extend(defaults,options);
        var current = $(this);
        var imgArray;
        init();
        resize();
        scroll();
        //初始化
        function init(){
            //注册样式
            $('head').append([
            '<style>',
            '.tz-container{text-align:center;width:'+ opts.boxWidth +'}',
            '.tz-column-item,.tz-column-item-blank{width: '+ opts.columnWidth +';display:inline-block;vertical-align: top;margin:0 '+ opts.spacing +';}',
            '.tz-column-item .tz-img-box{width: 100%;border: 1px solid #ccc;display: block;padding: 4px;margin:calc('+ opts.spacing + ' + ' + opts.spacing +') 0;box-sizing: border-box;}',
            '.tz-column-item img{width:100%;border: none;}',
            '</style>'
            ].join(''));
            //初始化当前容器
            current.addClass('tz-container').html("");
            imgArray = opts.imgUrl.concat();
            var viewPortWidth = current.width();
            var columnWidth = 0;
            if(opts.columnWidth.indexOf('px') >= 0){
                columnWidth = parseInt(opts.columnWidth);
            }else if(opts.columnWidth.indexOf('%') >= 0){
                columnWidth = viewPortWidth * parseInt(opts.columnWidth)/100;
            }
            if(opts.spacing.indexOf('px') >= 0){
                columnWidth = columnWidth + parseInt(opts.spacing)*2;
            }else if(opts.spacing.indexOf('%') >= 0){
                columnWidth = columnWidth + viewPortWidth * parseInt(opts.spacing)/100*2;
            }
            var number = Math.floor(viewPortWidth / columnWidth);
            var minColumn = number;
            if(imgArray.length < number) minColumn = imgArray.length;
            for(var i = 0;i<minColumn;i++){
                var imgUrl = getImgUrl();
                if(imgUrl){
                    current.append('<span class="tz-column-item"><a class="tz-img-box"><img src="'+imgUrl+'"></a></span>');
                }
            }
            (function loadMoreRow() {
                var containerHeight = current.height();
                var viewPortHeight = $(window).height();
                if(containerHeight < viewPortHeight){
                    var loadDoneCount = 0;
                    for(var i = 0;i<minColumn;i++){
                        var imgUrl = getImgUrl();
                        if(imgUrl){
                            var ele = '<a class="tz-img-box"><img src="'+imgUrl+'"></a>';
                            current.find('.tz-column-item').eq(i).append(ele);
                            $(ele).find('img').load(function () {
                                loadDoneCount ++;
                            })
                        }
                    }
                    var t = setInterval(function () {
                        if(loadDoneCount == minColumn){
                            clearInterval(t);
                            loadMoreRow()
                        }
                    },100);
                }else{
                    fixShort();
                }
            })();
            current.append('<span class="tz-column-item-blank"></span>');
        }
        //resize
        function resize(){
            $(window).resize(function(){
                if(current.find(".tz-column-item").length){
                    var containerY = current[0].offsetTop;
                    var BlankY = current.find(".tz-column-item-blank")[0].offsetTop;
                    var lastY = current.find(".tz-column-item").last()[0].offsetTop;
                    //如果填充列跳到首行或最后一列跳到第二行，则重新渲染
                    if(containerY == BlankY || lastY != containerY) init();
                }
            });
        }
        //scroll
        function scroll(){
            $(window).scroll(function(){
                var bodyHeight = $("html,body").height();
                var windowHeight = $(window).height();
                var scrollTop = $(window).scrollTop();
                if(bodyHeight - windowHeight - scrollTop < 20){
                    var loadDoneCount = 0;
                    current.find(".tz-column-item").each(function(){
                        var imgUrl = getImgUrl();
                        if(imgUrl){
                            var element = '<a class="tz-img-box"><img src="'+imgUrl+'"></a>';
                            $(this).append(element);
                            $(element).find('img').load(function () {
                                loadDoneCount ++;
                            })
                        }
                    });
                    var t = setInterval(function () {
                        if(loadDoneCount == current.find(".tz-column-item").length){
                            clearInterval(t);
                            fixShort();
                        }
                    },100);
                }
            });
        }
        //为最短的列再额外添加一张图片
        function fixShort() {
            var itemList = current.find('.tz-column-item');
            var minHeight = current.height();
            var minIndex = 0;
            var maxHeight = current.height();
            itemList.each(function (index) {
                if($(this).height() < minHeight){
                    minHeight = $(this).height();
                    minIndex = index;
                }
                if($(this).height() > maxHeight){
                    maxHeight = $(this).height();
                }
            });
            if(maxHeight - minHeight > 200){
                console.log('fix');
                var imgUrl = getImgUrl();
                if(imgUrl){
                    $(itemList[minIndex]).append('<a class="tz-img-box"><img src="'+imgUrl+'"></a>');
                }
            }
        }
        //生成图片路径
        function getImgUrl(){
            if(imgArray.length == 0) return false;
            if(opts.random){
                var random = parseInt(Math.random()*imgArray.length);
                var imgUrl = imgArray.splice(random,1);
                return opts.imgUrlPrefix + imgUrl;
            }else{
                return opts.imgUrlPrefix + imgArray.shift();
            }
        }
    };
})(jQuery);